#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    void print(vector<int>& vec)
    {
        for (auto& e : vec) cout << e << ' ';
        cout << endl;
    }
    int closestMeetingNode(vector<int>& edges, int node1, int node2) {
        int n = edges.size();
        vector<int> dp1(n, -1), dp2(n, -1);
        for (int i = node1, boot = 0; i != -1 && dp1[i] == -1; i = edges[i])
        {
            dp1[i] = boot++;
        }
        for (int i = node2, boot = 0; i != -1 && dp2[i] == -1; i = edges[i])
        {
            dp2[i] = boot++;
        }
        int res = -1;
        for (int i = 0; i < n; i++)
        {
            if (dp1[i] != -1 && dp2[i] != -1 && (res == -1 || max(dp1[i], dp2[i]) < max(dp1[res], dp2[res])))
                res = i;
        }
        return res;
    }
};